package dao

import (
	"context"
	"encoding/json"
	"fmt"
	"gbox-one-machine/models"
	"net/http"
)

// http path
const (
	getEventsPath = "/api/v1/resource_center/broker/event"
	addEventsPath = "/api/v1/resource_center/broker/event"
)

// GetEventsCond GetEvents cond
type GetEventsCond struct {
	BeginID  string
	Page     int64
	PageSize int64
}

type getEventsResp struct {
	ReturnCode   int                  `json:"returnCode"`
	ErrorMessage string               `json:"errorMessage"`
	Result       *getEventsRespResult `json:"result"`
}

type getEventsRespResult struct {
	Total int64           `json:"total"`
	Data  []*models.Event `json:"data"`
}

// GetEvents get events
func (d *Dao) GetEvents(ctx context.Context, cond *GetEventsCond) ([]*models.Event, error) {

	resResp := new(getEventsResp)

	url := fmt.Sprintf("%s?page=%d&pageSize=%d", d.resCenterHost+getEventsPath, cond.Page, cond.PageSize)

	if cond.BeginID != "" {
		url = fmt.Sprintf("%s&beginID=%s", url, cond.BeginID)
	}

	resp, err := d.http().R().SetContext(ctx).Get(url)
	if err != nil {
		return nil, fmt.Errorf("HTTP request err: %s", err)
	}

	if resp.StatusCode() != http.StatusOK {
		return nil, fmt.Errorf("HTTP status %s", resp.Status())
	}

	if err := json.Unmarshal(resp.Body(), resResp); err != nil {
		return nil, err
	}

	if resResp.ReturnCode != 0 {
		return nil, fmt.Errorf("Errcode: %d, Msg: %s", resResp.ReturnCode, resResp.ErrorMessage)
	}

	return resResp.Result.Data, nil
}

type addEventsResp struct {
	ReturnCode   int      `json:"returnCode"`
	ErrorMessage string   `json:"errorMessage"`
	Result       []string `json:"result"`
}

// AddEvents get bind node
func (d *Dao) AddEvents(ctx context.Context, events []*models.Event) error {

	resResp := new(addEventsResp)

	resp, err := d.http().R().SetContext(ctx).SetBody(events).Post(d.resCenterHost + addEventsPath)
	if err != nil {
		return fmt.Errorf("HTTP request err: %s", err)
	}

	if resp.StatusCode() != http.StatusOK {
		return fmt.Errorf("HTTP status %s", resp.Status())
	}

	if err := json.Unmarshal(resp.Body(), resResp); err != nil {
		return err
	}

	if resResp.ReturnCode != 0 {
		return fmt.Errorf("Errcode: %d, Msg: %s", resResp.ReturnCode, resResp.ErrorMessage)
	}

	return nil
}
